<template>
  <div class="user-edit">
    <h1>编辑个人信息</h1>

    <div v-if="loading" class="loading">加载中...</div>

    <div v-if="errorMessage" class="error-message">
      <span class="error-icon">⚠️</span>
      <span class="error-text">{{ errorMessage }}</span>
    </div>

    <form v-if="userInfo" @submit.prevent="handleSubmit" class="profile-form">
      <div class="form-group">
        <label for="username">用户名</label>
        <input
          id="username"
          v-model="userInfo.username"
          type="text"
          required
        />
        <span v-if="!userInfo.username.trim() && errorMessage.includes('用户名')" class="field-error">用户名不能为空</span>
      </div>

      <div class="form-group">
        <label for="sex">性别</label>
        <select
          id="sex"
          v-model="userInfo.sex"
          required
        >
          <option value="男">男</option>
          <option value="女">女</option>
        </select>
      </div>

      <div class="form-group">
        <label for="age">年龄</label>
        <input
          id="age"
          v-model.number="userInfo.age"
          type="number"
          min="0"
          max="120"
        />
        <span v-if="(userInfo.age < 0 || userInfo.age > 120) && errorMessage.includes('年龄')" class="field-error">年龄必须在0-120之间</span>
      </div>

      <div class="form-group">
        <label for="phone">电话</label>
        <input
          id="phone"
          v-model="userInfo.phone"
          type="tel"
          pattern="^1[3-9]\d{9}$"
          placeholder="请输入11位手机号码"
        />
        <span v-if="userInfo.phone && !/^1[3-9]\d{9}$/.test(userInfo.phone) && errorMessage.includes('电话')" class="field-error">请输入有效的11位手机号码</span>
      </div>

      <!-- 密码修改区域 -->
      <div class="password-section">
        <h3>修改密码</h3>
        <div class="form-group">
          <label for="newPassword">新密码</label>
          <input
            id="newPassword"
            v-model="newPassword"
            type="password"
            placeholder="不修改请留空"
            minlength="6"
          />
          <span v-if="newPassword && newPassword.length < 6 && errorMessage.includes('密码')" class="field-error">密码长度不能少于6位</span>
        </div>

        <div class="form-group">
          <label for="confirmPassword">确认新密码</label>
          <input
            id="confirmPassword"
            v-model="confirmPassword"
            type="password"
            placeholder="不修改请留空"
          />
          <span v-if="confirmPassword && newPassword !== confirmPassword && errorMessage.includes('密码')" class="field-error">两次输入的密码不一致</span>
        </div>
      </div>

      <div class="form-actions">
        <button type="submit" class="save-btn" :disabled="isSubmitting">
          <span v-if="isSubmitting">保存中...</span>
          <span v-else>保存修改</span>
        </button>
        <RouterLink to="/user-profile" class="cancel-btn" :disabled="isSubmitting">取消</RouterLink>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { RouterLink, useRouter } from 'vue-router';

const router = useRouter();
const userInfo = ref(null);
const loading = ref(true);
const errorMessage = ref('');
const newPassword = ref('');
const confirmPassword = ref('');
const isSubmitting = ref(false);

// 从localStorage获取用户信息
onMounted(() => {
  try {
    const storedUser = localStorage.getItem('currentUser');
    if (storedUser) {
      userInfo.value = JSON.parse(storedUser);
    } else {
      errorMessage.value = '未找到用户信息，请先登录';
      router.push('/login');
    }
  } catch (error) {
    errorMessage.value = '加载用户信息失败';
  } finally {
    loading.value = false;
  }
});

// 处理表单提交
const handleSubmit = async () => {
  if (isSubmitting.value) return;
  isSubmitting.value = true;
  errorMessage.value = '';

  try {
    // 基础验证
    if (!userInfo.value.username.trim()) {
      errorMessage.value = '用户名不能为空';
      return;
    }

    if (userInfo.value.age === null || userInfo.value.age === undefined || isNaN(userInfo.value.age) || userInfo.value.age < 0 || userInfo.value.age > 120) {
      errorMessage.value = '年龄必须在0-120之间';
      return;
    }

    if (userInfo.value.phone && !/^1[3-9]\d{9}$/.test(userInfo.value.phone)) {
      errorMessage.value = '请输入有效的11位手机号码';
      return;
    }

    // 密码验证
    if (newPassword.value) {
      if (newPassword.value.length < 6) {
        errorMessage.value = '密码长度不能少于6位';
        return;
      }
      if (newPassword.value !== confirmPassword.value) {
        errorMessage.value = '两次输入的密码不一致';
        return;
      }
      // 更新密码
      userInfo.value.password = newPassword.value;
    }

    // 提交到后端更新用户信息
    const response = await fetch('http://localhost:8080/api/users/update', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(userInfo.value),
    });

    const result = await response.json();
    if (!response.ok || !result.success) {
      throw new Error(result.message || '更新用户信息失败');
    }

    // 更新localStorage中的用户信息
    localStorage.setItem('currentUser', JSON.stringify(userInfo.value));

    // 显示成功消息并返回个人中心页面
    alert('用户信息更新成功');
    router.push('/user-profile');
  } catch (error) {
    errorMessage.value = '保存失败：' + (error.message || '未知错误');
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
.user-edit {
  max-width: 600px;
  margin: 80px auto 2rem;
  padding: 2rem;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.loading {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.error-message {
  color: #d43f3a;
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  padding: 10px 15px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.error-icon {
  margin-right: 8px;
  font-size: 16px;
}

.profile-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

label {
  font-weight: 500;
  color: #333;
}

input, select {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
}

input:focus, select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.form-actions {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
}

.save-btn {
  flex: 1;
  padding: 12px;
  background-color: #667eea;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.save-btn:hover:not(:disabled) {
  background-color: #5a67d8;
}

.cancel-btn {
  flex: 1;
  padding: 12px;
  text-align: center;
  background-color: #f5f5f5;
  color: #333;
  text-decoration: none;
  border-radius: 6px;
  font-size: 16px;
  transition: background-color 0.3s;
}

.cancel-btn:hover:not(:disabled) {
  background-color: #e5e5e5;
}

.password-section {
  margin-top: 1.5rem;
  padding-top: 1rem;
  border-top: 1px solid #eee;
}

.password-section h3 {
  margin-top: 0;
  color: #666;
}

.field-error {
  color: #d43f3a;
  font-size: 12px;
  margin-top: 4px;
}

.save-btn:disabled, .cancel-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}
</style>